package web.servlet.userlist.web.servelt;

import javax.imageio.ImageIO;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.Random;

/**
 * @Author: Administrator
 * @Date: 2020/5/28 18:57
 */
@WebServlet("/checkCode")
public class CheckCode extends HttpServlet {
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        /* 显示验证码：
         *  1、创建一图片对象（内存） BufferedImage
         *  2、美化图片
         *     使用画笔： Graphics
         *      setColor设置颜色
         *     1）填充背景色   fillRect
         *     2）画边框  drawRect
         *     3）生成随机字符，写验证码（写字符 drawString）
         *       3.1） 将生成的验证码保存在session域
         *     4）画干扰线  drawLine
         *  3、将图片输出到页面展示 ImageIO */
        int width=80;
        int height=30;
        BufferedImage image=new BufferedImage(width,height,BufferedImage.TYPE_INT_RGB);
        Graphics g=image.getGraphics();
        g.setColor(Color.GRAY);
        g.fillRect(0,0,width,height);
        g.drawRect(0,0,width-1,height-1);

        String str="abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
        Random random=new Random();
        StringBuilder sb=new StringBuilder();
        //设置画笔颜色为黄色
        g.setColor(Color.YELLOW);
        //设置字体的小大
        g.setFont(new Font("黑体",Font.BOLD,24));
        for (int i = 1; i <=4; i++) {
            int index = random.nextInt(str.length());
            char ch = str.charAt(index);
            sb.append(ch);
            g.drawString(ch+"",width/6*i,height*2/3);
        }
        /* 将验证码保存在session域*/
        String checkCode_session=sb.toString();
        req.getSession().setAttribute("checkCode_session",checkCode_session);

        g.setColor(Color.GREEN);
        for (int i = 0; i <6 ; i++) {
            int x1 = random.nextInt(width);
            int x2 = random.nextInt(width);
            int y1 = random.nextInt(height);
            int y2 = random.nextInt(height);
            g.drawLine(x1,x2,y1,y2);
        }
        ImageIO.write(image,"jpg",resp.getOutputStream());
    }

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        this.doPost(req,resp);
    }
}
